using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using RiceShop.Models;
using RiceShop.Services;
using RiceShop.Extensions;

namespace RiceShop.Controllers
{
    /// <summary>
    /// 订单控制器 - 处理所有订单相关的 HTTP 请求
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        private readonly IOrderService _orderService;
        private readonly ILogger<OrderController> _logger;

        /// <summary>
        /// 构造函数 - 通过依赖注入获取订单服务实例
        /// </summary>
        /// <param name="orderService">订单服务接口</param>
        /// <param name="logger">日志记录器</param>
        public OrderController(IOrderService orderService, ILogger<OrderController> logger)
        {
            _orderService = orderService;
            _logger = logger;
        }

        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="pageSize">每页显示的订单数量，默认10条</param>
        /// <param name="pageIndex">当前页码，默认第1页</param>
        /// <param name="status">订单状态过滤，可选参数</param>
        /// <returns>分页后的订单列表</returns>
        [HttpGet("list")]
        public async Task<IActionResult> GetOrders(
           [FromQuery] int pageSize = 10,
           [FromQuery] int pageIndex = 1,
           [FromQuery] OrderStatus? status = null)
        {
            var orders = await _orderService.GetOrdersAsync(pageSize, pageIndex, status);
            return Ok(orders);
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>订单详细信息</returns>
        [HttpGet("detail/{orderNo}")]
        public async Task<ActionResult<OrderDetailResponse>> GetOrderDetail(string orderNo)
        {
            var orderDetail = await _orderService.GetOrderDetailAsync(orderNo);
            return Ok(orderDetail);
        }

        /// <summary>
        /// 创建新订单
        /// </summary>
        /// <param name="request">创建订单请求模型，包含商品信息、收货地址等</param>
        /// <returns>新创建的订单编号</returns>
        [HttpPost("create")]
        public async Task<IActionResult> CreateOrder([FromBody] CreateOrderRequest request)
        {
            var orderNo = await _orderService.CreateOrderAsync(request);
            return Ok(new { orderNo });
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="orderNo">要取消的订单编号</param>
        /// <returns>操作结果</returns>
        [HttpPost("{orderNo}/cancel")]
        public async Task<IActionResult> CancelOrder(string orderNo)
        {
            await _orderService.CancelOrderAsync(orderNo);
            return Ok();
        }

        /// <summary>
        /// 确认收货
        /// </summary>
        /// <param name="orderNo">要确认收货的订单编号</param>
        /// <returns>操作结果</returns>
        [HttpPost("{orderNo}/confirm")]
        public async Task<IActionResult> ConfirmOrder(string orderNo)
        {
            await _orderService.ConfirmOrderAsync(orderNo);
            return Ok();
        }

        /// <summary>
        /// 获取物流信息
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>订单的物流跟踪信息</returns>
        [HttpGet("{orderNo}/logistics")]
        public async Task<IActionResult> GetLogistics(string orderNo)
        {
            var logistics = await _orderService.GetLogisticsInfoAsync(orderNo);
            return Ok(logistics);
        }

        /// <summary>
        /// 申请售后服务
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <param name="request">售后服务请求信息，包含售后类型、原因等</param>
        /// <returns>操作结果</returns>
        [HttpPost("{orderNo}/afterService")]
        public async Task<IActionResult> ApplyAfterService(
            string orderNo,
            [FromBody] AfterServiceRequest request)
        {
            await _orderService.ApplyAfterServiceAsync(orderNo, request);
            return Ok();
        }

        /// <summary>
        /// 获取用户订单数量
        /// </summary>
        /// <returns>订单数量</returns>
        [HttpGet("count")]
        [Authorize]
        public async Task<ActionResult<ApiResponse<object>>> GetOrderCount()
        {
            try
            {
                var userId = User.GetUserId();
                if (userId == 0)
                {
                    return Unauthorized(new ApiResponse<object>(401, "用户未登录", null));
                }

                var count = await _orderService.GetOrderCountByUserIdAsync(userId);
                
                return Ok(new ApiResponse<object>(200, "获取订单数量成功", new { count }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取订单数量失败");
                return StatusCode(500, new ApiResponse<object>(500, "获取订单数量失败", null));
            }
        }


    }
}